<template>
    <search-bar v-if="actionshandle?.searchbar.state">
        <el-form ref="searchFormModel" :inline="true" :model="searchFormline">
            <template v-for="(item,key,index) of searchForm" :key="index">
                <el-form-item :label="item.label" :prop="item.prop">
                    <el-input v-if="item.elmentuiType == 'text' || !item.elmentuiType " v-model="searchFormline[item.prop]" clearable :placeholder="item.placeholder" />
                    <el-input-number
                        v-if="item.elmentuiType == 'number'"
                        v-model="searchFormline[item.prop]"
                        :min="item.min"
                        :max="item.max"
                        controls-position="right"
                        :placeholder="item.placeholder"
                    />
                    <el-date-picker
                        v-if="item.elmentuiType == 'date'"
                        v-model="searchFormline[item.prop]"
                        :type="item.dataType"
                        :placeholder="item.placeholder"
                    />
                    <!-- <el-select v-if="item.elmentuiType == 'select'" v-model="searchFormline[item.prop]" filterable clearable :placeholder="item.placeholder">
                        <el-option
                            v-for="el in item.option()"
                            :key="el.value"
                            :label="el.label"
                            :value="el.value"
                        />
                    </el-select> -->
                    <selectTreeVue v-if="item.elmentuiType == 'select'" v-model="searchFormline[item.prop]" :options="item.option()"  clearable :placeholder="item.placeholder" />
                </el-form-item>
            </template>
            <el-form-item>
                <el-button type="primary"  bg @click="searchChange">查询</el-button>
            </el-form-item>
            <el-form-item>
                <el-button  @click="resetForm(searchFormModel)">重置</el-button>
            </el-form-item>
        </el-form>
    </search-bar>
    <NTable
        ref="curdTable"
        :loading="tableLoading"
        :actions="actionshandle"
        :is-pagination="true"
        :is-handle="true"
        :table-data="props.data"
        :table-cols="props.options.column"
        :table-handles="tableHandles"
        :pagination="props.page"
        :isSelection ="props.options.isSelection || false"
        @refresh="refreshChange"
        @select="select"
        :disable-height="props.disableHeight"
    >
        <template #actions="row">
            <slot name="actions" v-bind="row" />
            <el-button
                v-if="actionshandle?.edit.state"
                :icon="actionshandle?.edit.icon || Edit"
                :type="actionshandle?.edit.type || 'warning'"
                :size="actionshandle?.edit.size || 'default'"
                :plain="actionshandle?.del.plain"
                @click.prevent="updateRow(row.row)"
            >
                {{ actionshandle?.edit?.text ? actionshandle.edit.text : "修改" }}
            </el-button>
            <el-button
                v-if="actionshandle?.del.state"
                :icon="actionshandle?.del.icon || Delete"
                :type="actionshandle?.del.type || 'danger'"
                :size="actionshandle?.del.size || 'default'"
                :plain="actionshandle?.del.plain"
                @click.prevent="deleteRow(row.row)"
            >
                {{ actionshandle?.del?.text ? actionshandle.del.text : "删除" }}
            </el-button>
        </template>
        <template #menu-left>
            <slot name="tableHandles" />
        </template>

        <!-- //当配置参数type== customCol时，自定义插槽里面的显示内容 -->
        <template v-for="(item,index) in customColList" :key="index" #[item.prop]="scope">
            <slot :name="item.prop" v-bind="scope" />
        </template>
    </NTable>

    <NModal ref="nModalEleAdd" title="添加/修改属性" width="800px">
        <AddAttribute :close="closeAndRefresh" :submit="addAndUpdate" :edit-form="editForm" :tem-data="temData" />
    </NModal>
</template>

<script setup>
import AddAttribute from './dialog/add.attribute.vue';
import { computed, onMounted, ref, useSlots,getCurrentInstance  } from 'vue';
import { Upload,Check,Delete,Edit,Message,Search,Star,Plus } from '@element-plus/icons-vue';
import selectTreeVue from '../TreeSelect/index.vue'
import NTable from '../NTable/index.vue';
import searchBar from '../SearchBar/index.vue';
import NModal from '../NModal/index.vue'

const { proxy } = getCurrentInstance();


const searchFormModel = ref(null)
const curdTable =  ref(null)
const props = defineProps({
    data: {
        type: Array, default: () => []
    },
    options: {
        type: Object, default: () => {}
    },
    page: {
        type: Object, default: () => {}
    },
    disableHeight:{
        type:Boolean,
        default:false
    }
})
const emit = defineEmits(['rowSave', 'rowUpdate', 'rowDel', 'refreshChange', 'searchChange','select'])

const ade_dict = ['add', 'del', 'edit']
const other_dict = ['refresh', 'filter', 'fullScreen', 'pagination', 'searchbar', 'layout']

const tableLoading = ref(false)
// 搜索框字段
const searchFormline = ref({})



const customColList = computed(() => {
    return configOptions.value.column.filter(res => {
        return res?.type && res?.type == 'customCol'
    })
})

let searchForm = computed(() => {
    // 参数带search=true 过滤出来当搜索form
    if (props.options?.column.length < 1) {
        return []
    }

    return props.options?.column.filter(row => {
        if (row?.search && row?.search == true) {
            let obj = {}
            obj[row['prop']] = ''
            searchFormline.value = { ...searchFormline.value, ...obj }
            return row
        }
    })
})

// 用于增加和修改功能
let editFormline = ref({})
// 过滤需要增加修改的字段unedit==true时不显示编辑
let editForm = computed(() => {
    if (props.options?.column.length < 1) {
        return []
    }

    return props.options?.column.filter(row => {
        if (!row?.unedit || row?.unedit == false) {
            let obj = {}
            obj[row['prop']] = ''
            editFormline.value = { ...editFormline.value, ...obj }
            return row
        }
    })
})

// 控制组件展示
let actionshandle =  computed(() => {
    let defaultconfig = { 'actionSlot': { 'state': false, 'text': '操作' }, 'add': { 'state': false, 'text': '新增' }, 'del': { 'state': false, 'text': '删除' }, 'edit': { 'state': false, 'text': '修改' }, 'refresh': { 'state': false, 'text': '' }, 'layout': { 'state': false, 'text': '' }, 'filter': { 'state': false, 'text': '' }, 'fullScreen': { 'state': false, 'text': '' }, 'pagination': { 'state': false, 'text': '' }, 'searchbar': { 'state': false, 'text': '' } }
    if (props.options?.actions.length < 1) {
        return defaultconfig
    }
    props.options.actions.map(row => {
        // 增删改字典
        const all_dict = [...ade_dict, ...other_dict]
        if (typeof row === 'string' && all_dict.includes(row)) {
            // 传参字符串时判断
            defaultconfig[row] = {
                state: true,
                text: ''
            }
        } else if (typeof row === 'object' && row?.name && ade_dict.includes(row.name)) {
            defaultconfig[row.name] = {
                state: true,
                text: row.text,
                ...row.confirm
            }
        }

    })

    // 判断actions插槽是否为空，不为空改defaultconfig的actions为true
    if (useSlots().actions) {
        defaultconfig.actionSlot.state = true
    }
    return defaultconfig
})

const tableHandles = computed(() => {
    // 暂时只有新增，后续可能回有导出导入功能
    if (actionshandle.value.add.state) {
        return [
            {
                label: actionshandle.value.add.text ? actionshandle.value.add.text : '新增', icon:Plus, type: 'success', handle: row => {
                    addTemplate()
                }
            }
        ]
    }
    return []
})

const configOptions = computed(() => {
    if (props?.options) {
        return props.options
    } else {
        return {}
    }
})

const temData = ref(null)

// 搜索点击
function searchChange() {
    props.page.currentPage = 1
    tableLoading.value = true
    emit('searchChange', searchFormline.value, done => {
        tableLoading.value = false
    })
}

// 重置搜索条件
const resetForm = formEl => {
    if (!formEl) return
    formEl.resetFields()
}

function refreshChange(res = null) {
    tableLoading.value = true
    emit('refreshChange', res, done => {
        tableLoading.value = false
    })
}

function deleteRow(row) {
    proxy.$confirm(
        actionshandle.value.del.message ? actionshandle.value.del.message : '是否删除？',
        actionshandle.value.del.title ? actionshandle.value.del.title : '提示',
        {
            confirmButtonText: actionshandle.value.del.confirmButtonText ? actionshandle.value.del.confirmButtonText : '确定',
            cancelButtonText: actionshandle.value.del.cancelButtonText ? actionshandle.value.del.cancelButtonText : '取消',
            type: 'warning'
        }
    ).then(() => {
        emit('rowDel', row)

    }).catch(() => {

    })

}

// 更新
function updateRow(row) {
    // row.actions = 'edit'
    temData.value = { ...row, ...{ _actionsType: 'update' } }
    proxy.$refs.nModalEleAdd.open()
}

// 新增
function addTemplate() {
    temData.value = {
        _actionsType: 'add'
    }
    proxy.$refs.nModalEleAdd.open()
}

// 关掉新增修改
function closeAndRefresh() {
    proxy.$refs.nModalEleAdd.close()
}

// 新增和更新
async function addAndUpdate(res) {
    tableLoading.value = true
    if (res._actionsType == 'update') {
        // 删除自带的属性，不提交
        Reflect.deleteProperty(res, '_actionsType')
        // 更新
        emit('rowUpdate', res, done => {
            // 回调函数的方法体.处理自己的业务.
            tableLoading.value = false
            proxy.$refs.nModalEleAdd.close()
        })
    }

    if (res._actionsType == 'add') {
        // 删除自带的属性，不提交
        Reflect.deleteProperty(res, '_actionsType')
        // 新增
        emit('rowSave', res, done => {
            // 回调函数的方法体.处理自己的业务.
            tableLoading.value = false
            proxy.$refs.nModalEleAdd.close()
        })
    }
}

//表格多选值
function select(rows, row) {
    emit('select',rows,row)
}

onMounted(() => {
    console.log(curdTable.value)
})

// 外部暴露的接口
defineExpose({
    addTemplate
})
</script>

<style scoped lang="scss">
:deep(.el-date-editor){
    width: 100%;
}
:deep(.el-select){
    width: 100%;
}

.asterisk-left{
    margin-right: 10px !important;
}
</style>
